package com.itcast.googleplay;

import java.io.File;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.itcast.googleplay.R;
import com.itcast.googleplay.bean.AppInfo;
import com.itcast.googleplay.holder.AppDesHolder;
import com.itcast.googleplay.holder.AppInfoHolder;
import com.itcast.googleplay.holder.AppPicHolder;
import com.itcast.googleplay.holder.AppSafeHolder;
import com.itcast.googleplay.http.HttpApi;
import com.itcast.googleplay.protocol.DetailProtocol;
import com.itcast.googleplay.ui.LoadingPage;
import com.itcast.googleplay.ui.LoadingPage.ResultState;
import com.itcast.googleplay.utils.UIUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.sample.download.DownloadInfo;
import com.lidroid.xutils.sample.download.DownloadManager;
import com.lidroid.xutils.sample.download.DownloadService;

public class DetailActivity extends BaseActivity {
	private FrameLayout flAppInfo;
	private LoadingPage loadingPage;
	private String packageName;
	private AppInfo data;
	private FrameLayout flAppSafe;
	private ProgressBar pbProgress;
	private TextView tvState;
	private DownloadManager downloadManager;
	private DownloadStateListener downloadStateListener = new DownloadStateListener();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail);

		initActionBar();

		packageName = getIntent().getStringExtra("packagename");

		loadingPage = new LoadingPage(UIUtils.getContext()) {
			@Override
			public ResultState onload() {
				return loadData();
			}

			@Override
			public View onCreateSuccessView() {
				return onSuccessedView();
			}
		};
		if (loadingPage != null) {
			loadingPage.show();
		}
		setContentView(loadingPage);
	}

	private void initActionBar() {
		ActionBar actionBar = getSupportActionBar();
		// 2.设置标题和图标
		actionBar.setTitle("谷歌市场详情");
		actionBar.setIcon(R.drawable.ic_launcher);
		// 3.让ActionBar的home按钮可以被点击
		actionBar.setDisplayHomeAsUpEnabled(true);// 显示home按钮
		actionBar.setDisplayShowHomeEnabled(true);// 让home按钮可以被点击
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	protected ResultState loadData() {
		DetailProtocol detailProtocol = new DetailProtocol();
		data = detailProtocol.getData("detail", -1, "&packageName="
				+ packageName);
		if (data != null) {
			return ResultState.STATE_SUCCESSED;
		}
		return ResultState.STATE_ERROR;
	}

	protected View onSuccessedView() {
		downloadManager = DownloadService.getDownloadManager(UIUtils.getContext());
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data.getId()+"");
		if(downloadInfo!=null){
	         if (downloadInfo.getHandler() != null) {
	             RequestCallBack callBack = downloadInfo.getHandler().getRequestCallBack();
	             if (callBack instanceof DownloadManager.ManagerCallBack) {
	                 DownloadManager.ManagerCallBack managerCallBack = (DownloadManager.ManagerCallBack) callBack;
	                 managerCallBack.setBaseCallBack(downloadStateListener);
	             }
	         }
		}
		View view = UIUtils.inflate(R.layout.activity_detail);
		ScrollView scrollView = (ScrollView) view.findViewById(R.id.scrollview);
		// 设置进度条的控件
		pbProgress = (ProgressBar) view.findViewById(R.id.pb_progress);
		// 设置状态的控件
		tvState = (TextView) view.findViewById(R.id.tv_state);

		refreshUI();

		pbProgress.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				download();
			}
		});

		flAppInfo = (FrameLayout) view.findViewById(R.id.fl_app_info);
		AppInfoHolder appInfoHolder = new AppInfoHolder();
		View appHolderView = appInfoHolder.getConvertView();
		appInfoHolder.setData(data);
		flAppInfo.addView(appHolderView);

		flAppSafe = (FrameLayout) view.findViewById(R.id.fl_app_safe);
		AppSafeHolder appSafeHolder = new AppSafeHolder();
		View viewHolderSafe = appSafeHolder.getConvertView();
		appSafeHolder.setData(data);
		flAppSafe.addView(viewHolderSafe);

		FrameLayout flAppPic = (FrameLayout) view.findViewById(R.id.fl_app_pic);
		AppPicHolder appPicHolder = new AppPicHolder();
		View picHolderView = appPicHolder.getConvertView();
		appPicHolder.setData(data);
		flAppPic.addView(picHolderView);

		FrameLayout flAppDes = (FrameLayout) view.findViewById(R.id.fl_app_des);
		AppDesHolder appDesHolder = new AppDesHolder();
		View appDesView = appDesHolder.getConvertView();
		appDesHolder.setData(data);
		appDesHolder.setScrollView(scrollView);
		flAppDes.addView(appDesView);

		return view;
	}

	// 此方法用于处理下载相关逻辑
	protected void download() {
		// sd卡被挂载
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			// 获取sd卡路径
			String target = Environment.getExternalStorageDirectory()
					+File.separator +"GooglePlay"
					+File.separator+"download"
					+File.separator+data.packageName + ".apk";
					
			DownloadInfo downloadInfo = downloadManager
					.getDownloadInfoByAppId(data.getId() + "");

			if (downloadInfo != null) {
				// 断点续传下载
				HttpHandler.State state = downloadInfo.getState();
				switch (state) {
				case WAITING:// 等待状态的时候,点击后取消下载
				case STARTED:// 准备开始的时候,点击后取消下载
				case LOADING:// 正在下载的时候,点击后取消下载
					try {
						downloadManager.stopDownload(downloadInfo);
					} catch (DbException e) {
						e.printStackTrace();
					}
					break;
				case CANCELLED:// 取消下载,点击后继续下载
				case FAILURE:// 下载失败,点击后继续下载
					try {
						downloadManager.resumeDownload(downloadInfo,
								downloadStateListener);
					} catch (DbException e) {
						e.printStackTrace();
					}
					break;
				case SUCCESS:
					// 下载成功,点击后安装apk
					installApk();
					break;
				}
			} else {
				// 重头开始下载
				try {
					downloadManager.addNewDownload(
							data.getId() + "",
							HttpApi.BASEURL + "download?name="
									+ data.getDownloadUrl(), data.name, target,
							true, false, downloadStateListener);
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
			
			refreshUI();
		}
	}

	private void installApk() {
		Toast.makeText(UIUtils.getContext(), "可以安装了.......", 0).show();
	}

	class DownloadStateListener extends RequestCallBack<File> {

		@Override
		public void onFailure(HttpException arg0, String progress) {
			// 下载失败
			refreshUI();
		}

		@Override
		public void onSuccess(ResponseInfo<File> file) {
			// 下载成功
			refreshUI();
		}

		@Override
		public void onLoading(long total, long current, boolean isUploading) {
			System.out.println("onLoading........");
			// 下载过程中
			refreshUI();
			super.onLoading(total, current, isUploading);
		}

		@Override
		public void onStart() {
			// 开始下载
			refreshUI();
			super.onStart();
		}

		@Override
		public void onCancelled() {
			// 下载取消
			refreshUI();
			super.onCancelled();
		}
	}

	public void refreshUI() {
		DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId(data
				.getId() + "");

		if (downloadInfo == null) {
			tvState.setText("下载");
		} else {
			String appId = downloadInfo.getAppId();
			if (Integer.parseInt(appId) == data.getId()) {
				switch (downloadInfo.getState()) {
				case CANCELLED:
					if(downloadInfo
							.getFileLength()>0){
						int progress = (int) (downloadInfo.getProgress() * 100 / downloadInfo
								.getFileLength());
						pbProgress.setProgress(progress);
					}
					tvState.setText("继续");
					break;
				case FAILURE:
					tvState.setText("重试");
					break;
				case LOADING:
					if(downloadInfo
							.getFileLength()>0){
						int progressloading = (int) (downloadInfo.getProgress() * 100 / downloadInfo
								.getFileLength());
						pbProgress.setProgress(progressloading);
						tvState.setText(progressloading + "%");
					}
					break;
				case STARTED:
					tvState.setText("准备下载");
					break;
				case SUCCESS:
					tvState.setText("安装");
					pbProgress.setProgress(100);
					break;
				case WAITING:
					tvState.setText("等待");
					break;
				}
			}
		}
	}
}
